package com.palm.platform;

import cn.beecp.BeeDataSource;
import com.palm.core.Module;
import com.palm.core.util.Captcha;
import org.noear.solon.Solon;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.validation.annotation.NoRepeatSubmitValidator;

import javax.sql.DataSource;
import java.util.Objects;

/**
 * 平台模块
 */
@Configuration
@Import(scanPackages = {"com.palm.platform.service","com.palm.platform.controller"})
public class PlatformModule implements Module {

    @Bean
    public DataSource db1(@Inject("${datasource}") BeeDataSource ds) {

        return ds;
    }

    @Init
    public void init() {

        Current.init(Solon.global());

        boolean only_number= Solon.cfg().getBool("captcha.only_number",false);
        //验证码支持
        Solon.global().add("captcha", MethodType.GET, ctx -> Captcha.captcha(ctx,only_number));
        //自动跳转首页
        Solon.global().add("/", MethodType.GET, ctx -> ctx.redirect("index.html"));
        NoRepeatSubmitValidator.instance.setChecker((anno, ctx, submitHash, limitSeconds) -> {
            String tk=ctx.cookie("_ft");

            if(tk==null){
                ctx.cookieSet("_ft",submitHash);
                return true;
            }
            if(Objects.equals(tk,submitHash)){
                return false;
            }else{
                ctx.cookieSet("_ft",submitHash);
                return true;
            }
//            String psh = (String) ctx.session("@per_submitHash");
//            Long pt = ctx.session("@per_submit_time", 0L);
//            ctx.sessionSet("@per_submitHash", submitHash);
//            ctx.sessionSet("@per_submit_time", System.currentTimeMillis() / 1000);
//            if (psh == null) {
//                return true;
//            }
//            if (psh.equals(submitHash)) {
//                return limitSeconds > System.currentTimeMillis() / 1000 - pt;
//            }
//            return true;
        });
        //注册菜单
        regMenu(PlatformMenu.class);
    }

}
